package org.example.wx.user.service.impl;

import org.example.wx.user.entity.ShippingAddress;
import org.example.wx.user.repository.ShippingAddressRepository;
import org.example.wx.user.service.ShippingAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class ShippingAddressServiceImpl implements ShippingAddressService {

    @Autowired
    private ShippingAddressRepository shippingAddressRepository;

    @Override
    @Transactional
    public ShippingAddress createAddress(Long userId, ShippingAddress address) {
        // 设置用户ID
        address.setUserId(userId);
        
        // 如果设置为默认地址，先将用户其他地址设为非默认
        if (address.getIsDefault() != null && address.getIsDefault()) {
            shippingAddressRepository.updateAllToNonDefault(userId);
        }
        
        // 如果用户没有地址，第一个地址自动设为默认
        long addressCount = shippingAddressRepository.countByUserIdAndStatus(userId);
        if (addressCount == 0) {
            address.setIsDefault(true);
        }
        
        return shippingAddressRepository.save(address);
    }

    @Override
    @Transactional
    public ShippingAddress updateAddress(Long userId, Long addressId, ShippingAddress address) {
        Optional<ShippingAddress> existingOpt = shippingAddressRepository.findByIdAndUserIdAndStatus(addressId, userId);
        if (!existingOpt.isPresent()) {
            throw new RuntimeException("地址不存在或无权限修改");
        }
        
        ShippingAddress existing = existingOpt.get();
        
        // 更新字段
        existing.setRecipientName(address.getRecipientName());
        existing.setPhoneNumber(address.getPhoneNumber());
        existing.setProvince(address.getProvince());
        existing.setCity(address.getCity());
        existing.setCounty(address.getCounty());
        existing.setDetailedAddress(address.getDetailedAddress());
        existing.setAddressTag(address.getAddressTag());
        
        // 处理默认地址设置
        if (address.getIsDefault() != null && address.getIsDefault() && !existing.getIsDefault()) {
            shippingAddressRepository.updateAllToNonDefault(userId);
            existing.setIsDefault(true);
        }
        
        return shippingAddressRepository.save(existing);
    }

    @Override
    @Transactional
    public boolean deleteAddress(Long userId, Long addressId) {
        // 验证地址是否存在且属于用户
        Optional<ShippingAddress> addressOpt = shippingAddressRepository.findByIdAndUserIdAndStatus(addressId, userId);
        if (!addressOpt.isPresent()) {
            return false;
        }
        
        ShippingAddress address = addressOpt.get();
        boolean wasDefault = address.getIsDefault();
        
        // 逻辑删除
        int deleted = shippingAddressRepository.deleteByIdAndUserId(addressId, userId);
        
        // 如果删除的是默认地址，需要设置新的默认地址
        if (deleted > 0 && wasDefault) {
            List<ShippingAddress> remainingAddresses = shippingAddressRepository.findByUserIdAndStatusOrderByIsDefaultDescUpdatedAtDesc(userId);
            if (!remainingAddresses.isEmpty()) {
                ShippingAddress newDefault = remainingAddresses.get(0);
                newDefault.setIsDefault(true);
                shippingAddressRepository.save(newDefault);
            }
        }
        
        return deleted > 0;
    }

    @Override
    public Optional<ShippingAddress> getAddressById(Long userId, Long addressId) {
        return shippingAddressRepository.findByIdAndUserIdAndStatus(addressId, userId);
    }

    @Override
    public List<ShippingAddress> getUserAddresses(Long userId) {
        return shippingAddressRepository.findByUserIdAndStatusOrderByIsDefaultDescUpdatedAtDesc(userId);
    }

    @Override
    public Optional<ShippingAddress> getDefaultAddress(Long userId) {
        return shippingAddressRepository.findDefaultByUserId(userId);
    }

    @Override
    @Transactional
    public boolean setDefaultAddress(Long userId, Long addressId) {
        Optional<ShippingAddress> addressOpt = shippingAddressRepository.findByIdAndUserIdAndStatus(addressId, userId);
        if (!addressOpt.isPresent()) {
            return false;
        }
        
        // 先将所有地址设为非默认
        shippingAddressRepository.updateAllToNonDefault(userId);
        
        // 设置指定地址为默认
        ShippingAddress address = addressOpt.get();
        address.setIsDefault(true);
        shippingAddressRepository.save(address);
        
        return true;
    }

    @Override
    public boolean validateAddressOwnership(Long userId, Long addressId) {
        return shippingAddressRepository.findByIdAndUserIdAndStatus(addressId, userId).isPresent();
    }

    @Override
    public long getUserAddressCount(Long userId) {
        return shippingAddressRepository.countByUserIdAndStatus(userId);
    }
}
